package com.halloon.android.task;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;

import org.apache.http.HttpEntity;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;

import com.halloon.android.data.SettingsManager;
import com.halloon.android.util.ImageUtil;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ImageLoadTask extends AsyncTask<String, Float, Bitmap> {
	private ImageView pdView;
	private Context context;
	private TextView loading;
	
	private float progressPercent;
	
	public ImageLoadTask(Context context, ImageView pdView, TextView loading){
		this.pdView = pdView;
		this.loading = loading;
	}
	
	@Override
	protected void onPreExecute(){
		loading.setVisibility(View.VISIBLE);
	}

	@Override
	protected Bitmap doInBackground(String... params) {
		if(isCancelled()){
			return null;
		}
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(params[0]);
		InputStream is = null;
		ByteArrayOutputStream baos = null;
		try{
			HttpResponse httpResponse = httpClient.execute(httpGet);
			printHttpResponse(httpResponse);
			HttpEntity httpEntity = httpResponse.getEntity();
			long length = httpEntity.getContentLength();
			is = httpEntity.getContent();
			if(is != null){
				baos = new ByteArrayOutputStream();
				byte[] buf = new byte[128];
				int read = -1;
				int count = 0;
				while((read = is.read(buf)) != -1){
					baos.write(buf, 0, read);
					count += read;
					publishProgress(count * 1.0f / length);
				}
				byte[] data = baos.toByteArray();
				Bitmap bit = BitmapFactory.decodeByteArray(data, 0, data.length);
				
				return bit;
			}
		}catch(ClientProtocolException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			try{
				if(baos != null){
					baos.close();
				}
				if(is != null){
					is.close();
				}
			}catch(IOException e){
				e.printStackTrace();
			}
		}
		return null;
	}
	
	@Override
	protected void onProgressUpdate(Float... progress){
		DecimalFormat df = null;
		try{
			df = (DecimalFormat) NumberFormat.getPercentInstance();
		}catch(ClassCastException e){
			e.printStackTrace();
		}
		df.applyPattern("0.00%");
		loading.setText(df.format(progress[0]));
		progressPercent = progress[0];
	}
	
	@Override
	protected void onPostExecute(Bitmap bit){
		if(!isCancelled()){
			if(bit != null){
				pdView.setImageBitmap(bit);
				ImageUtil iu = new ImageUtil(context);
				float tmp_scale = 1;
				
				int width = SettingsManager.getInstance(context).getScreenWidth();
				int height = SettingsManager.getInstance(context).getScreenHeight();
				
				if(bit.getWidth() > width){
					tmp_scale = (float) width / (float) bit.getWidth();
					iu.matrix.postScale(tmp_scale, tmp_scale, 0, 0);
				}
				
				if(bit.getHeight() * tmp_scale > height && bit.getWidth() < bit.getHeight()){
					iu.matrix.postTranslate((width - (bit.getWidth() * tmp_scale)) / 2, 0); 
				}else{
					iu.matrix.postTranslate((width - (bit.getWidth() * tmp_scale)) / 2, (height - (bit.getHeight() * tmp_scale)) / 2); 
				}
				pdView.setImageMatrix(iu.matrix);
				pdView.setOnTouchListener(iu.getImageTranslateListener());
				loading.setVisibility(View.GONE);
			}else{
				Toast.makeText(context, "载入图片失败", Toast.LENGTH_LONG).show();
			}
		}
	}
	
	public float getProgress(){
		return progressPercent;
	}
	
	private void printHttpResponse(HttpResponse httpResponse){
		Header[] headerArr = httpResponse.getAllHeaders();
		for(int i = 0; i < headerArr.length; i++){
			Header header = headerArr[i];
		}
		HttpParams params = httpResponse.getParams();
	}

}
